package p15.code;

import java.util.*;
import java.util.concurrent.*;

public class invokeAllStudy {

    static ExecutorService executorService = Executors.newFixedThreadPool(2);

    public static List<Integer> getRankedTravelQuotes(Integer travel, Set<Random> randomSet,
                                               Comparator<Integer> ranking, long time, TimeUnit unit) throws InterruptedException{

        List<QuoteTask> tasks = new ArrayList<>();

        for(Random random:randomSet){
            tasks.add(new QuoteTask(random,travel));
        }

        List<Future<Integer>> futures = executorService.invokeAll(tasks,time,unit);

        List<Integer> quotes = new ArrayList<>(tasks.size());

        for(Future<Integer> f:futures){
            try{
                quotes.add(f.get());
            }
            catch (ExecutionException e){
                //任务执行出错
                quotes.add(-1);
            }catch (CancellationException e){
                //超时取消
                quotes.add(-2);
            }
        }
        //quotes.sort(ranking);
        return quotes;
    }

    public static void main(String[] args) throws InterruptedException {
        Set<Random> randomSet = new HashSet<>();
        for(int i=0;i<10;i++){
            randomSet.add(new Random());
        }
        List<Integer> result =  getRankedTravelQuotes(1000, randomSet, (o1, o2) -> o1-o2,1,TimeUnit.MILLISECONDS);
        System.out.println(result);
    }

}

class QuoteTask implements Callable<Integer> {

    private final Random random;
    private final Integer travel;

    QuoteTask(Random random, Integer travel) {
        this.random = random;
        this.travel = travel;
    }

    @Override
    public Integer call() throws Exception {
        Thread.sleep(1);
        return random.nextInt(travel);
    }
}
